//
//  CarInputChooseBrandVC.m
//  New_Runway
//
//  Created by mack on 2018/3/15.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CarInputChooseBrandVC.h"
#import "CarBrandModel.h"
#import "KingOfCarCell.h"
#import "DSectionIndexItemView.h"
#import "DSectionIndexView.h"
#import "CarInputChooseSeriesVC.h"

#import "CarInputChooseModel.h"

@interface CarInputChooseBrandVC ()<UITableViewDelegate,UITableViewDataSource,DSectionIndexViewDelegate,DSectionIndexViewDataSource>
@property(nonatomic, strong) UITableView *tableview;
//@property (nonatomic, strong)NSIndexPath *selIndex;//上一次选中的索引

@property (nonatomic, strong) NSMutableArray *indexTitles;
@property (strong, nonatomic) DSectionIndexView *sectionIndexView;
@property (nonatomic, strong) NSIndexPath *selectedIndexPath;
@property (nonatomic, strong)NSMutableArray <BrandResult *>*dataArray;

@end

@implementation CarInputChooseBrandVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBarView.titleLabel.text = @"品牌";
    self.view.backgroundColor = kColorWhite();
    [self initTableview];
    [self _initIndexView];

    [self loadCarBrand];
}
-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    _tableview.estimatedRowHeight = 0;
    _tableview.estimatedSectionHeaderHeight = 0;
    _tableview.estimatedSectionFooterHeight = 0;
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    self.tableview.backgroundColor = MAIN_COLOR();
    //    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableview registerClass:[KingOfCarCell class] forCellReuseIdentifier:@"KingOfCarCell"];
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).mas_offset(self.navH);
        make.bottom.equalTo(weakSelf.view).mas_equalTo(-self.BotH);
        make.left.right.equalTo(weakSelf.view);
    }];
}
- (void)_initIndexView
{
    _sectionIndexView = [[DSectionIndexView alloc] init];
    _sectionIndexView.backgroundColor = [UIColor clearColor];
    _sectionIndexView.dataSource = self;
    _sectionIndexView.delegate = self;
    _sectionIndexView.isShowCallout = YES;
    _sectionIndexView.calloutViewType = CalloutViewTypeForUserDefined;
    _sectionIndexView.calloutDirection = SectionIndexCalloutDirectionLeft;
    _sectionIndexView.calloutMargin = 20.f;
    [self.view addSubview:self.sectionIndexView];
    
}

#define kSectionIndexWidth 20.f
- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    _sectionIndexView.frame = CGRectMake(CGRectGetWidth(self.tableview.frame) - kSectionIndexWidth, self.navH + 100, kSectionIndexWidth, Screen_height - self.navH - 200);
    [_sectionIndexView setBackgroundViewFrame];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataArray.count;
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    

    BrandResult *result = self.dataArray[section];
    return result.brandInfo.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KingOfCarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KingOfCarCell"];
    cell.tintColor = MAIN_NAV_COLOR();
    BrandResult *result  = self.dataArray[indexPath.section];
    Brandinfo *info = [Brandinfo mj_objectWithKeyValues:result.brandInfo[indexPath.row]];
    cell.CarName.text = info.brandName;
    [cell.CarIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",info.brandLogo]]];
    
    if (self.selectedIndexPath == indexPath) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        cell.CarName.textColor = MAIN_NAV_COLOR();
        
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.CarName.textColor = MAIN_FONT_COLOR();
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    KingOfCarCell *celled = [tableView cellForRowAtIndexPath:self.selectedIndexPath];
    celled.accessoryType = UITableViewCellAccessoryNone;
    
    celled.CarName.textColor = MAIN_FONT_COLOR();
    //记录当前选中的位置索引
    self.selectedIndexPath = indexPath;
    //当前选择的打勾
    KingOfCarCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    cell.CarName.textColor = MAIN_NAV_COLOR();
    
    [self.tableview reloadData];
    
    [self cellDidClickWithIndex:indexPath];
}

- (void)cellDidClickWithIndex:(NSIndexPath *)indexPath {
    
   
    BrandResult *result  = self.dataArray[indexPath.section];
    Brandinfo *info = [Brandinfo mj_objectWithKeyValues:result.brandInfo[indexPath.row]];
    CarInputChooseSeriesVC *seriesVC = [[CarInputChooseSeriesVC alloc] init];

    CarInputChooseModel *model = [[CarInputChooseModel alloc] init];
    model.brandName = info.brandName;
    model.brandId = info.brandId;
    seriesVC.model = model;
    seriesVC.fromControllerClass = self.fromControllerClass;
//    seriesVC.carBrandName = info.brandName;
//    seriesVC.carBrandId = info.brandId;
//    seriesVC.tabIndex = self.tabIndex;
    [self.navigationController pushViewController:seriesVC animated:YES];
        
}

-(void)loadCarBrand{
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,carBrandApi];
    
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        [self.dataArray removeAllObjects];
        CarBrandModel *model = [CarBrandModel mj_objectWithKeyValues:response];
        for (NSDictionary *dic in model.result) {
            BrandResult *result = [BrandResult mj_objectWithKeyValues:dic];
            [self.dataArray addObject:result];
            [self.indexTitles addObject:result.initial];
        }
        [self.sectionIndexView reloadItemViews];
        [self.tableview reloadData];
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
    
    
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = UIColorHex(0xf5f5f5);
    UILabel *label = [[UILabel alloc] init];
    label.textColor = MAIN_FONT_COLOR();
    label.font = kFontSize(13);
    label.text = self.indexTitles[section];
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view).mas_offset(16);
        make.centerY.equalTo(view);
    }];
    
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
-(NSMutableArray *)indexTitles{
    if (!_indexTitles) {
        _indexTitles = [[NSMutableArray alloc] init];
    }
    return _indexTitles;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark DSectionIndexViewDataSource && delegate method
- (NSInteger)numberOfItemViewForSectionIndexView:(DSectionIndexView *)sectionIndexView
{
    return self.indexTitles.count;
}

- (DSectionIndexItemView *)sectionIndexView:(DSectionIndexView *)sectionIndexView itemViewForSection:(NSInteger)section
{
    DSectionIndexItemView *itemView = [[DSectionIndexItemView alloc] init];
    itemView.titleLabel.text = [self.indexTitles objectAtIndex:section];
    itemView.titleLabel.font = [UIFont systemFontOfSize:12];
    itemView.titleLabel.textColor = [UIColor darkGrayColor];
    itemView.titleLabel.highlightedTextColor = MAIN_NAV_COLOR();
    itemView.titleLabel.shadowColor = [UIColor whiteColor];
    itemView.titleLabel.shadowOffset = CGSizeMake(0, 1);
    
    return itemView;
}

- (UIView *)sectionIndexView:(DSectionIndexView *)sectionIndexView calloutViewForSection:(NSInteger)section
{
    UILabel *label = [[UILabel alloc] init];
    
    label.frame = CGRectMake(0, 0, 40, 40);
    
    label.backgroundColor = [UIColor clearColor];
    label.textColor = MAIN_NAV_COLOR();
    label.font = [UIFont boldSystemFontOfSize:24];
    label.text = [self.indexTitles objectAtIndex:section];
    label.textAlignment = NSTextAlignmentCenter;
    
    //    [label.layer setCornerRadius:label.frame.size.width/2];
    //    [label.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    //    [label.layer setBorderWidth:3.0f];
    //    [label.layer setShadowColor:[UIColor blackColor].CGColor];
    //    [label.layer setShadowOpacity:0.8];
    //    [label.layer setShadowRadius:5.0];
    //    [label.layer setShadowOffset:CGSizeMake(2.0, 2.0)];
    
    
    return label;
}

- (NSString *)sectionIndexView:(DSectionIndexView *)sectionIndexView
               titleForSection:(NSInteger)section
{
    return [self.indexTitles objectAtIndex:section];
}

- (void)sectionIndexView:(DSectionIndexView *)sectionIndexView didSelectSection:(NSInteger)section
{
    [self.tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}



@end
